<?php

class Basic{
    private static $config;
    private static $_instance;
    public  static $route;
    public  $db;
    public  $controller;
    public  $action;

    private function __construct(){
        global $config;
        self::$config = $config;
    }

    public function run($config){
    	Debug::record("Begin Application");
        self::$route = Route::get_instance();
        $this->loadController();
        $this->execAction();
    }


    static public function app(){
        if(self::$_instance == null){
            self::$_instance = new Basic();
        }
        return self::$_instance;
    }

    public function import($name){
        $base = self::$config['base'];
        require_once($base['root'].nameToPath($name));
    }

    public function getConfigs(){
        $config = self::$config;
        return $config;
    }



    public function setParams($data=array()){
        $config = $this -> getConfigs();
        $config['params'] = $data;
    }

    public function addParams($data=array()){
        $config = $this -> getConfigs();
        if($config['params']){
            $config['params'] = array_merge($config['params'],$data);
        }
    }


    public function getRoute(){
        return self::$route;
    }

    public function loadController(){
        $controller = $this->getRoute()->controller;
        $name = 'controller.'.$controller;
        $this->import('system.class.controller');
        $this->import($name);
        $controller = ucfirst($controller).'Controller';
        $this->controller =  new $controller;
    }

    public function execAction(){
        $actionName = ucfirst($this->getRoute()->action).'Action';
        $controllerName = ucfirst($this->getRoute()->controller).'Controller';
        $refClass = new ReflectionClass($controllerName);
        if($refClass->hasMethod($actionName)){
            $refMethod = $refClass->getMethod($actionName);
            $refMethod->invoke($this->controller);
        }

    }


    public function createDb(){
        $config = $this->getConfigs();
        $dbConfig = $config['db'];
        $dataTypes = array_keys($dbConfig);
        if(count($dataTypes)>0){
            $priorType = $dataTypes[0];
            switch($priorType){
                case "mysql":
                    return new Mysql();break;
                case "mongo":
                    return new Mongo();break;
            }
        }
        return false;
    }

    public function getVersion(){
        return '1.0beta';
    }


}
